package com.relytosoft.mizar.analyze.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.relytosoft.dubhe.common.api.entity.system.SysFile;
import com.relytosoft.dubhe.common.api.service.RemoteFileService;
import com.relytosoft.dubhe.common.core.config.properties.DubheFileProperties;
import com.relytosoft.dubhe.common.file.entity.UploadResult;
import com.relytosoft.dubhe.common.file.exception.FileException;
import com.relytosoft.dubhe.common.file.factory.FileFactory;
import com.relytosoft.dubhe.common.file.service.FileStrategy;
import com.relytosoft.mizar.analyze.base.constant.FileSuffixConstants;
import com.relytosoft.mizar.analyze.base.constant.SymbolConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 上传文件
 *
 * @Author SunLi
 * @Date: 2022/4/24 18:57
 * @Version 1.0
 */
@Service
public class RemoteFileServiceImpl implements RemoteFileService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private DubheFileProperties dubheFileProperties;

    @Override
    public SysFile upload(String name, String originalFilename, String contentType, byte[] file, int fileType) {

        FileStrategy storage = FileFactory.instance(dubheFileProperties);
        try {
            String suffix =
                    StrUtil.isNotBlank(originalFilename)
                            ? StrUtil.sub(originalFilename, originalFilename.lastIndexOf(SymbolConstants.DOT), originalFilename.length())
                            : SymbolConstants.DOT + FileSuffixConstants.JPG;
            UploadResult uploadResult = storage
                    .uploadSuffix(file, suffix, contentType);
            SysFile sysFile = new SysFile();
            sysFile.setName(uploadResult.getFilename());
            sysFile.setUrl(uploadResult.getUrl());
            return sysFile;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new FileException("上传文件失败");
        }
    }


}
